package net.caixiaomi.info.ui.order;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;

import net.caixiaomi.info.R;
import net.caixiaomi.info.adapter.OrderInfoAdapter;
import net.caixiaomi.info.app.CommonApp;
import net.caixiaomi.info.base.BaseActivity;
import net.caixiaomi.info.base.progressbar.CircularProgressBar;
import net.caixiaomi.info.life.EWMDialog;
import net.caixiaomi.info.model.BaseCallModel;
import net.caixiaomi.info.model.CommonEvent;
import net.caixiaomi.info.model.OrderInfoItem;
import net.caixiaomi.info.model.OrderInfoModel;
import net.caixiaomi.info.net.RequestService;
import net.caixiaomi.info.net.ResponseCallback;
import net.caixiaomi.info.net.ResponseError;
import net.caixiaomi.info.net.RetrofitManage;
import net.caixiaomi.info.ui.dialog.ShareDialogFragment;
import net.caixiaomi.info.ui.football.PlayFootballActivity;
import net.caixiaomi.info.util.Constants;
import net.caixiaomi.info.util.EventWhat;
import net.caixiaomi.info.util.FileHelper;
import net.caixiaomi.info.util.SchemeUtil;
import net.caixiaomi.info.util.ToastUtil;
import net.caixiaomi.info.util.WeiXinUtils;
import net.caixiaomi.smartrefresh.layout.SmartRefreshLayout;
import net.caixiaomi.smartrefresh.layout.api.RefreshLayout;
import net.caixiaomi.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.BigDecimal;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;

import static android.R.id.list;

/**
 * 订单详情
 */

public class OrderInfoActivity extends BaseActivity implements View.OnClickListener, OnRefreshListener {

    @BindView(R.id.btn_next)
    View mBtnNext;
    @BindView(list)
    RecyclerView mListView;
    @BindView(R.id.progress)
    CircularProgressBar mProgress;
//    @BindView(R.id.we_share)
//    TextView shareTv;

    @BindView(R.id.refresh)
    SmartRefreshLayout mRefreshLayout;

    private ImageView mIcon;
    private TextView mName;
    private TextView mPrice;//花费钱
    private TextView mPreLotteryPrice;//预测中奖钱
    private TextView mStatus;//订单状态
    private TextView mPlanStatus;//方案状态
    private TextView mLotteryPriceInfo;//中奖金额
    private TextView mPlanResult;//方案结果
    private TextView mPassWay;//过关方式
    private TextView mTreble;//倍数
    private TextView mOrderNum;//方案编号
    private TextView mCreateTime;//创建时间
    private TextView mPickTime;//店主接单
    private TextView mPrintTicketTime;//店主出票
    private TextView mPayInfo;//支付信息

    private OrderInfoAdapter mAdapter;
    private String mOrderId;
    private OrderInfoModel mOrderInfo;

    private String addFriendsQRBarUrl;

    @OnClick(R.id.moni_share)
    void shareMoni(){
        ShareDialogFragment shareDialog = new ShareDialogFragment();
        Bundle bundle = new Bundle();
        bundle.putString("data", mOrderInfo.getOrderSn());
        bundle.putBoolean("simpleMoni",true);
        shareDialog.setArguments(bundle);
        shareDialog.show(getSupportFragmentManager(), shareDialog.getClass().getName());
    }
    @OnClick(R.id.moni_ewm)
    void EWMMoni(){
        EWMDialog dialog=new EWMDialog(this);
        dialog.setImgUrl(addFriendsQRBarUrl);
        dialog.show();
        dialog.setCancelable(true);
    }

    /**
     * 接续预约
     */
    @OnClick(R.id.btn_next)
    void toContinue() {
//        if (mOrderInfo == null)
//            return;
//        if (TextUtils.equals(mOrderInfo.getDetailType(), "0")) {
//            Intent intent = new Intent(this, PlayFootballActivity.class);
//            intent.putExtra("playType", mOrderInfo.getLotteryPlayClassifyId());//因二选一玩法下单时改成了混合玩法，所以
//            intent.putExtra("lotteryId", mOrderInfo.getLotteryClassifyId());
//            intent.putExtra("playClassifyId", mOrderInfo.getLotteryPlayClassifyId());
//            startActivity(intent);
//        } else {
//            SchemeUtil.parseIntentUrl(this, mOrderInfo.getRedirectUrl(),"");
//        }
        ShareDialogFragment shareDialog = new ShareDialogFragment();
        Bundle bundle = new Bundle();
        bundle.putString("data", mOrderInfo.getOrderSn());
        bundle.putBoolean("simpleMoni",true);
        shareDialog.setArguments(bundle);
        shareDialog.show(getSupportFragmentManager(), shareDialog.getClass().getName());
    }

    @Override
    protected int layout() {
        return R.layout.act_order_info;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mOrderId = getIntent().getStringExtra("id");
        initView();
        loadData();

    }

    private void initView() {
        try {
            mRefreshLayout.setOnRefreshListener(this);
            View headerView = LayoutInflater.from(this).inflate(R.layout.header_order_info, null);
            mIcon = (ImageView) headerView.findViewById(R.id.image);
            mName = (TextView) headerView.findViewById(R.id.name);
            mPrice = (TextView) headerView.findViewById(R.id.price);
            mPreLotteryPrice = (TextView) headerView.findViewById(R.id.pre_lottery_price);
            mStatus = (TextView) headerView.findViewById(R.id.status);
            mPlanStatus = (TextView) headerView.findViewById(R.id.plan_status);
            mLotteryPriceInfo = (TextView) headerView.findViewById(R.id.lottery_info);
            mPlanResult = (TextView) headerView.findViewById(R.id.plan_result);

            View footerView = LayoutInflater.from(this).inflate(R.layout.footer_order_info, null);
            mPassWay = (TextView) footerView.findViewById(R.id.pass_way);
            mTreble = (TextView) footerView.findViewById(R.id.treble);
            footerView.findViewById(R.id.btn_look).setOnClickListener(this);
            mOrderNum = (TextView) footerView.findViewById(R.id.order_num);
            mCreateTime = (TextView) footerView.findViewById(R.id.create_time);
            mPickTime = (TextView) footerView.findViewById(R.id.pick_time);
            mPrintTicketTime = (TextView) footerView.findViewById(R.id.print_ticket_time);
            mPayInfo = (TextView) footerView.findViewById(R.id.pay_info);

            mAdapter = new OrderInfoAdapter(null);
            mAdapter.addHeaderView(headerView);
            mAdapter.addFooterView(footerView);
            mListView.setLayoutManager(new LinearLayoutManager(this));
            mListView.setAdapter(mAdapter);

//            shareTv.setVisibility(View.VISIBLE);
//            shareTv.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View view) {
//            Bitmap b = Bitmap.createBitmap(mListView.getMeasuredWidth(), 3000, Bitmap.Config.ARGB_8888);
//            Canvas c = new Canvas(b);
//            c.drawColor(Color.WHITE);
//            mListView.layout(0, 0, mListView.getMeasuredWidth(), 3000);
//            mListView.draw(c);
//            WeiXinUtils.shareImage(OrderInfoActivity.this,b, SendMessageToWX.Req.WXSceneSession);
//                    FileHelper.saveBitmap(OrderInfoActivity.this,b,"erweima");
//                }
//            });

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void loadData() {
        JSONObject params = new JSONObject();
        params.put("orderId", mOrderId);
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel<OrderInfoModel>> orderDetail = requestService.getOrderDetail(params);
        orderDetail.enqueue(new ResponseCallback<BaseCallModel<OrderInfoModel>>(this) {
            @Override
            public void onSuccess(BaseCallModel<OrderInfoModel> data) {
                mRefreshLayout.finishRefresh();
                mProgress.setVisibility(View.GONE);
                mOrderInfo = data.data;
                bindData(mOrderInfo);
            }

            @Override
            public void onFail(ResponseError error) {
                mRefreshLayout.finishRefresh();
                mProgress.setVisibility(View.GONE);
                if (error.getCode() >= 300000 && error.getCode() <= 310000) {
                    ToastUtil.s(error.getMessage());
                }
            }

            @Override
            public void onError() {
                mRefreshLayout.finishRefresh();
                mProgress.setVisibility(View.GONE);
            }
        });
    }

    private void bindData(OrderInfoModel model) {
        try {
            Glide.with(this).load(model.getLotteryClassifyImg()).into(mIcon);
            StringBuilder stringBuilder = new StringBuilder();
//            stringBuilder.append(getString(R.string.C_MONEY_CHAT)).append(model.getTicketAmount());
            stringBuilder.append(model.getTicketAmount());
            String price = stringBuilder.toString();
            stringBuilder.setLength(0);

            mName.setText(model.getLotteryClassifyName());
            mPrice.setText(price);

            mStatus.setText(model.getProcessResult());
            mStatus.setVisibility(!TextUtils.isEmpty(model.getProcessResult()) ? View.VISIBLE : View.GONE);
            mStatus.setTextColor(ContextCompat.getColor(CommonApp.getInstance(), TextUtils.equals(model.getOrderStatus(), "5") ? R.color.orange_primary : R.color.primary_text));

            mPreLotteryPrice.setText(model.getForecastMoney());

            mPlanStatus.setText(model.getOrderStatusDesc());
            mPlanStatus.setTextColor(ContextCompat.getColor(CommonApp.getInstance(), TextUtils.equals(model.getOrderStatus(), "2") ? R.color.orange_secondary : R.color.primary_text));

            mPlanResult.setTextColor(ContextCompat.getColor(CommonApp.getInstance(), TextUtils.equals(model.getOrderStatus(), "5") ? R.color.orange_primary : R.color.primary_text));
            mPlanResult.setText(TextUtils.equals(model.getOrderStatus(), "5") ? getString(R.string.C_MONEY_CHAT) + model.getProcessStatusDesc() : model.getProcessStatusDesc());
            mPlanResult.setVisibility(!TextUtils.isEmpty(model.getProcessStatusDesc()) ? View.VISIBLE : View.GONE);
            mLotteryPriceInfo.setVisibility(TextUtils.equals(model.getOrderStatus(), "5") ? View.VISIBLE : View.GONE);

            stringBuilder.setLength(0);
            stringBuilder.append(getString(R.string.C_PASS_WAY)).append(": ").append(model.getPassType());
            SpannableString spannableString = new SpannableString(stringBuilder);
            spannableString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(CommonApp.getInstance(), R.color.primary_text)), stringBuilder.length() - model.getPassType().length(), stringBuilder.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
            mPassWay.setText(spannableString);
            mPassWay.setVisibility(TextUtils.equals(model.getDetailType(), "0") ? View.VISIBLE : View.GONE);


            stringBuilder.setLength(0);
            String text = "";
            if (TextUtils.equals(model.getDetailType(), "0")) {
                stringBuilder.append(model.getCathectic());
            } else {
                stringBuilder.append(getString(R.string.C_TAKE_ORDER_BET, model.getBetNum(), model.getCathectic()));
            }
            text = stringBuilder.toString()+"倍";
            stringBuilder.setLength(0);
            stringBuilder.append(getString(R.string.C_PLAY_TREBLE)).append(": ").append(text);
            spannableString = new SpannableString(stringBuilder);
            spannableString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(CommonApp.getInstance(), R.color.primary_text)), stringBuilder.length() - text.length(), stringBuilder.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
            mTreble.setText(spannableString);

            stringBuilder.setLength(0);
            stringBuilder.append(getString(R.string.C_PLAN_NUM)).append(": ").append(model.getProgrammeSn());
            spannableString = new SpannableString(stringBuilder);
            spannableString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(CommonApp.getInstance(), R.color.primary_text)), stringBuilder.length() - model.getProgrammeSn().length(), stringBuilder.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
            mOrderNum.setText(spannableString);

            stringBuilder.setLength(0);
            stringBuilder.append(getString(R.string.C_ORDER_CREATE_TIME)).append(": ").append(model.getCreateTime());
            spannableString = new SpannableString(stringBuilder);
            spannableString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(CommonApp.getInstance(), R.color.primary_text)), stringBuilder.length() - model.getCreateTime().length(), stringBuilder.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
            mCreateTime.setText(spannableString);

            stringBuilder.setLength(0);
            stringBuilder.append(getString(R.string.C_ORDER_PICK_UP_TIME)).append(": ").append(model.getAcceptTime());
            spannableString = new SpannableString(stringBuilder);
            spannableString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(CommonApp.getInstance(), R.color.primary_text)), stringBuilder.length() - model.getAcceptTime().length(), stringBuilder.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
            mPickTime.setText(spannableString);

            stringBuilder.setLength(0);
            stringBuilder.append(getString(R.string.C_ORDER_OUT_TIME)).append(": ").append(model.getTicketTime());
            spannableString = new SpannableString(stringBuilder);
            spannableString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(CommonApp.getInstance(), R.color.primary_text)), stringBuilder.length() - model.getTicketTime().length(), stringBuilder.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
            mPrintTicketTime.setText(spannableString);

            stringBuilder.setLength(0);
            if (new BigDecimal(model.getThirdPartyPaid()).compareTo(new BigDecimal("0")) == 1) {
                stringBuilder.append(getString(R.string.C_THIRD_PAY, model.getPayName(), model.getThirdPartyPaid())).append("\n");
            }

            if (new BigDecimal(model.getSurplus()).compareTo(new BigDecimal("0")) == 1) {
                stringBuilder.append(getString(R.string.C_BALANCE_PAY, model.getSurplus())).append("\n");
            }

            if (new BigDecimal(model.getBonus()).compareTo(new BigDecimal("0")) == 1) {
                stringBuilder.append(getString(R.string.C_COUPON_PAY, model.getBonus())).append("\n");
            }
//            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
            mPayInfo.setText(stringBuilder);
            mAdapter.getData().clear();
            OrderInfoItem header = new OrderInfoItem();
            header.setItemType(Constants.ITEM_VIEW_HEADER);

            List<OrderInfoItem> matchInfos = model.getMatchInfos();
            matchInfos.add(0, header);
            for (OrderInfoItem infoItem : matchInfos) {
                infoItem.setDetailType(model.getDetailType());
            }

            mAdapter.addData(matchInfos);
            addFriendsQRBarUrl=model.getAddFriendsQRBarUrl();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onClick(View v) {
        if (mOrderInfo != null) {
            Intent intent = new Intent(this, PriceTicketPlanActivity.class);
            intent.putExtra("sn", mOrderInfo.getOrderSn());
            intent.putExtra("psn", mOrderInfo.getProgrammeSn());
            startActivity(intent);
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onPostEvent(CommonEvent event) {
        switch (event.getWhat()) {
            case EventWhat.EVENT_LOGIN:
                loadData();
                break;
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        try {
            mOrderId = intent.getStringExtra("id");
            loadData();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mOrderInfo = null;
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        loadData();
    }
}
